package com.ssish.saas.eccs.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;

import java.io.File;
import java.io.InputStream;
import java.util.List;

/**
 * @auther cuipan
 * @date 2019/5/7 10:56.
 */
public class OssUtils {

    public static String accessKeyId = "LTAINbgTZ6PA6bLd";
    public static String accessKeySecret = "xbTMcpICuaGihpWhkIjWp2c2hpJUdr";
    public static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    public static String bucketName = "test-ssish";

    private static OSSClient createOssClient(OssConfig config) {
        return new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
    }

    /**
     * 上传文件
     * 
     * @param config
     * @param file
     * @return
     */
    public static void upload(OssConfig config, File file) {
        OSSClient client = createOssClient(config);
        try {
            client.putObject(config.getBucketName(), config.getObjectName(), file);
        } finally {
            client.shutdown();
        }
    }

    /**
     * 上传流
     * 
     * @param config
     * @param
     * @return
     */
    public static void upload(OssConfig config, InputStream inputStream) {
        OSSClient client = createOssClient(config);
        try {
            client.putObject(config.getBucketName(), config.getObjectName(), inputStream);
        } finally {
            client.shutdown();
        }
    }

    /**
     * 上传流
     * 
     * @param config
     * @param
     * @return
     */
    public static InputStream get(OssConfig config) {
        OSSClient client = createOssClient(config);
        try {
            OSSObject ossObject = client.getObject(config.getBucketName(), config.getObjectName());
            if (ossObject != null && ossObject.getObjectContent() != null) {
                return ossObject.getObjectContent();
            } else {
                return null;
            }
        } finally {
            client.shutdown();
        }
    }

    public static void delete(OssConfig config) {
        OSSClient client = createOssClient(config);
        try {
            client.deleteObject(config.getBucketName(), config.getObjectName());
        } finally {
            client.shutdown();
        }
    }

    /**
     * 上传流
     * 
     * @param config
     * @param
     * @return
     */
    public static void listBuckets(OssConfig config) {
        OSSClient client = createOssClient(config);

        // 列举存储空间。
        List<Bucket> buckets = client.listBuckets();
        for (Bucket bucket : buckets) {
            System.out.println(" - " + bucket.getName());
        }

        // 关闭OSSClient。
        client.shutdown();
    }
}
